package com.gxp.web.controller;

import com.gxp.common.config.GxPConfig;
import com.gxp.common.core.controller.BaseController;
import com.gxp.common.core.domain.AjaxResult;
import com.gxp.common.core.domain.entity.SysRole;
import com.gxp.common.core.domain.entity.SysUser;
import com.gxp.common.utils.StringUtils;
import com.gxp.system.domain.ZkNmrFile;
import com.gxp.system.domain.ZknjServiceInstance;
import com.gxp.system.service.ISysMenuService;
import com.gxp.system.service.ISysUserService;
import com.gxp.system.service.IZkNmrFileService;
import com.gxp.system.service.IZknjServiceInstanceService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.Set;

/**
 * SpinStudioJ客户端数据处理控制器
 */
@Controller
@RequestMapping("/gxp")
public class SSJDataProcessController extends BaseController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private IZkNmrFileService nmrFileService;
    @Autowired
    private IZknjServiceInstanceService aServiceService;
    /**
     * 首次审计信息同步
     */
    @RequestMapping("/syncauditFirst.do")
    @ResponseBody
    public AjaxResult syncAuditsys(String hostId, boolean isAuditZip, MultipartFile auditFile){
        logger.info("First syncAuditsys hostId = {}, isAuditZip = {}, auditFile = {}", hostId, isAuditZip, auditFile.getOriginalFilename());
        String path = GxPConfig.getAuditsysPath(hostId);
        try {
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            if(isAuditZip){
                //压缩

            }
            auditFile.transferTo(new File(path + "/auditsys.txt"));
        } catch (IOException e) {
            logger.error(e.getMessage());
            error(e.getMessage()).put("code",400).put("data", "System Error");
        }
        return success().put("code", 200);
    }
    /**
     * 审计信息同步
     */
    @RequestMapping("/autosyncaudit.do")
    @ResponseBody
    public AjaxResult syncAuditsys( @Param("auditInfo")String auditInfo, @Param("zipFlag")boolean isAuditZip, @Param("hostId")String hostId){
        logger.info("SyncAuditsys hostId = {}, isAuditZip = {}, auditInfo length = {}", hostId, isAuditZip, auditInfo.length());
        String auditsysPath = GxPConfig.getAuditsysPath(hostId);
        File file = new File(auditsysPath);
        if(!file.exists()){
            file.mkdirs();
        }
        File auditsysFile = new File(auditsysPath + "/auditsys.txt");
        try {
            if(isAuditZip){
                //压缩

            }else {
                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(auditsysFile, true), "UTF-8");
                writer.write(auditInfo);
                writer.close();
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            System.out.println(e.getMessage());
            return error();
        }
        return success().put("code", 200);
    }

    /**
     * SpinStudioJ获取用户权限(60s询问一次)
     */
    @RequestMapping("/userpermission.do")
    @ResponseBody
    public AjaxResult getUserPermission(@Param("username")String username){
        logger.info("SSJ getUserPermission username = {}", username);
        StringBuffer msgSb = new StringBuffer();
        if (StringUtils.isEmpty(username)) {
            logger.error("SSJ getUserPermission username is empty");
            return AjaxResult.error(msgSb.append("failed to get username").toString());
        }
        SysUser user = userService.selectUserByLoginName(username);
        SysRole role = user.getRoles().get(0);
        Set<String> rolePerms = menuService.selectPermsNameByRoleId(role.getRoleId());
        msgSb.append(role.getRoleName()).append("-").append(StringUtils.join(rolePerms, "&"));
        logger.info("SSJ getUserPermission username = {}, role = {}, perms = {}", username, role.getRoleName(), StringUtils.join(rolePerms, "&"));
        return success(msgSb.toString()).put("code", 200);
    }

    /**
     * 下载实验数据
     */
    @RequestMapping("/downloadExpData.do")
    public ResponseEntity<Resource> downloadExpData(@Param("expcode")String expcode){
        logger.info("SSJ downloadExpData expcode = {}", expcode);
        try {
            //根据expcode获取服务
            ZknjServiceInstance service = aServiceService.selectZkServiceInstanceByExpcode(expcode);
            if(service == null){
                logger.error("SSJ downloadExpData service not found for expcode = {}", expcode);
                return ResponseEntity.notFound().build();
            }
            ZkNmrFile nmrFile = nmrFileService.selectZkNmrFileByFileId(service.getNmrfileId());
            String realFileName = nmrFile.getFileName();
            String realFilePath = nmrFile.getFilePathGxp() ;
            String profilePath = GxPConfig.getProfile();
            realFilePath = profilePath + "/" + realFilePath;
            File file = new File(realFilePath);
            if (!file.exists()) {
                logger.error("SSJ downloadExpData file not found: {}", realFilePath);
                return ResponseEntity.notFound().build();
            }
            InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
            return ResponseEntity.ok()
                    .contentLength(file.length())  // 文件大小
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + URLEncoder.encode(realFileName, "UTF-8") + "\"")
                    .body(resource);
        } catch (Exception e) {
            logger.error("SSJ downloadExpData error: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

    }
}
